package dk.modified.reshary;

import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import dk.modified.reshary.GlobalState.TrackerName;

public class CommentActivity extends Activity {

	ListView listView;
	TextView txt_no_comments;
	Button cmd_post;
	int comment_mediaId;
	CommentActivityAdapter adapter;
	Comment clickedComment;
	int clickedPosition;
	private PopupWindow reportCommentPopupWindow;
	private View popup_shadow;
	private ArrayList<ReportCategories> arrayList;
	private Boolean isInitial;
	private Button cmd_comment_retry;
	private ProgressBar prgbar;
	private SwipeRefreshLayout swipe_container;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_comment);

		isInitial = true;

		Tracker t = ((GlobalState) getApplication())
				.getTracker(TrackerName.APP_TRACKER);
		t.setScreenName("ReShary Comments");
		t.send(new HitBuilders.AppViewBuilder().build());
		getActionBar().setDisplayHomeAsUpEnabled(true);
		String title = getResources()
				.getString(R.string.title_activity_comment);
		Util.setActionBar(this, title);
		listView = (ListView) findViewById(R.id.listview);
		swipe_container = (SwipeRefreshLayout) findViewById(R.id.swipe_container);

		listView.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				int topRowVerticalPosition = (listView == null || listView
						.getChildCount() == 0) ? 0 : listView.getChildAt(0)
						.getTop();
				swipe_container.setEnabled(topRowVerticalPosition >= 0);
			}
		});

		swipe_container.setColorScheme(R.color.blue, R.color.blue,
				R.color.blue, R.color.blue);

		swipe_container.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				getComments(comment_mediaId, 0);
			}
		});

		registerForContextMenu(listView);
		cmd_post = (Button) findViewById(R.id.cmd_post);
		txt_no_comments = (TextView) findViewById(R.id.txt_no_comments);
		popup_shadow = (View) findViewById(R.id.popup_shadow);
		prgbar = (ProgressBar) findViewById(R.id.prgbar);
		cmd_comment_retry = (Button) findViewById(R.id.cmd_comment_retry);
		comment_mediaId = getIntent().getExtras().getInt("mediaid");

		SharedPreferences sharedpreferences = getSharedPreferences(
				"dk.modified.reshary", Context.MODE_PRIVATE);
		String report_posts = sharedpreferences.getString("report_posts", "");
		arrayList = formatCategories(report_posts);

		cmd_comment_retry.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				cmd_comment_retry.setVisibility(View.GONE);
				prgbar.setVisibility(View.VISIBLE);
				getComments(comment_mediaId, 0);
			}
		});

		cmd_post.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(),
						CommentsWriteActivity.class);
				i.putExtra("comment_mediaid", comment_mediaId);
				startActivityForResult(i,
						CommentsWriteActivity.ACTIVITY_REQUESTCODE);
				overridePendingTransition(R.anim.bottom_in, R.anim.top_out);
			}
		});

		getComments(comment_mediaId, 0);

	}

	private void getComments(int mediaId, final int position) {

		cmd_comment_retry.setVisibility(View.GONE);
		
		SharedPreferences sharedpreferences = getSharedPreferences(
				"dk.modified.reshary", Context.MODE_PRIVATE);
		String securitytoken = sharedpreferences.getString("securitytoken", "");
		String userId = sharedpreferences.getString("userid", "");

		RequestParams params = new RequestParams();
		params.put("securitytoken", securitytoken);
		params.put("userid", userId);
		params.put("mediaid", String.valueOf(mediaId));

		ResharyRestClient.post("get_comments/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {

						swipe_container.setRefreshing(false);
						isInitial = false;

						ArrayList<Comment> arrayOfComments = jsonToCommentsArray(content);
						prgbar.setVisibility(View.GONE);
						cmd_post.setVisibility(View.VISIBLE);

						if (arrayOfComments != null) {
							listView.setVisibility(View.VISIBLE);
							txt_no_comments.setVisibility(View.GONE);

							adapter = new CommentActivityAdapter(
									CommentActivity.this,
									R.layout.comments_listview_item,
									arrayOfComments);

							listView.setAdapter(adapter);
							if (position != 0) {
								listView.setSelection(position);
								swipe_container.setEnabled(false);
							}

							adapter.setOnButtonsClickedListener(new buttonsClickedListener() {

								@Override
								public void rateUpClicked(int i, Comment comment) {
									rateCommentUp(comment.getId());
								}

								@Override
								public void rateDownClicked(int i,
										Comment comment) {
									rateCommentDown(comment.getId());
								}

								@Override
								public void replyClicked(Comment comment,
										int position) {
									Intent i = new Intent(
											getApplicationContext(),
											CommentsWriteActivity.class);
									i.putExtra("position", position);
									i.putExtra("comment", comment);
									startActivityForResult(
											i,
											CommentsWriteActivity.ACTIVITY_REQUESTCODE);
									overridePendingTransition(R.anim.bottom_in,
											R.anim.top_out);
								}
							});

						} else {
							listView.setVisibility(View.GONE);
							txt_no_comments.setVisibility(View.VISIBLE);
						}

					}

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						swipe_container.setRefreshing(false);
						if (isInitial) {
							cmd_comment_retry.setVisibility(View.VISIBLE);
							cmd_post.setVisibility(View.GONE);
							prgbar.setVisibility(View.GONE);
						} else {
							Toast.makeText(getApplicationContext(),
									getString(R.string.network_error_comment),
									Toast.LENGTH_LONG).show();
						}

					}

				}, this);

	}

	private ArrayList<Comment> jsonToCommentsArray(String json) {
		ArrayList<Comment> commentsArr = new ArrayList<Comment>();

		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(json);
			JSONArray jsonCommentsArray = jsonObject.getJSONArray("comments");

			for (int i = 0; i < jsonCommentsArray.length(); i++) {

				JSONObject currentComment = jsonCommentsArray.getJSONObject(i);

				Comment comment = new Comment();
				comment.setId(currentComment.getInt("id"));
				comment.setMediaId(currentComment.getInt("mediaid"));
				comment.setParent(currentComment.getInt("parent"));
				comment.setUserid(currentComment.getInt("userid"));
				comment.setRating(currentComment.getInt("rating"));
				comment.setDate(currentComment.getString("dato"));
				comment.setComment(currentComment.getString("comment"));
				comment.setCommentMd5(currentComment.getString("commentmd5"));
				comment.setStatus(currentComment.getString("status"));
				comment.setReported(currentComment.getString("reported"));
				comment.setRealname(currentComment.getString("realname"));
				comment.setSocial(currentComment.getInt("social"));
				comment.setSocialId(currentComment.getInt("social_id"));
				comment.setProfilePic(currentComment.getString("profile_pic"));
				commentsArr.add(comment);
			}
			return commentsArr;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			return null;
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(R.anim.fadeout, R.anim.fadein);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
			return true;
		}
		if(item.getItemId() == R.id.action_refresh){
			if(isInitial){
				swipe_container.setRefreshing(true);
				getComments(comment_mediaId, 0);
			} else {
				swipe_container.setRefreshing(true);
				getComments(comment_mediaId, 0);
			}
		}
		return super.onOptionsItemSelected(item);
	}

	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == CommentsWriteActivity.ACTIVITY_REQUESTCODE) {
			if (resultCode == RESULT_OK) {

				if (data != null) {
					int position = data.getIntExtra("position", 0);
					getComments(comment_mediaId, position);
				} else {
					getComments(comment_mediaId, 0);
				}

			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.comments_contextmenu, menu);

		ListView lv = (ListView) v;
		AdapterView.AdapterContextMenuInfo acmi = (AdapterContextMenuInfo) menuInfo;

		clickedComment = (Comment) lv.getItemAtPosition(acmi.position);
		clickedPosition = acmi.position;
		MenuItem cmd_action = menu.findItem(R.id.cmd_action);

		SharedPreferences sharedpreferences = getSharedPreferences(
				"dk.modified.reshary", Context.MODE_PRIVATE);
		String userId = sharedpreferences.getString("userid", "");

		if (Integer.parseInt(userId) == clickedComment.getUserid()) {
			cmd_action.setTitle(getString(R.string.comment_delete));
		} else {
			cmd_action.setTitle(getString(R.string.comment_report));
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();

		SharedPreferences sharedpreferences = getSharedPreferences(
				"dk.modified.reshary", Context.MODE_PRIVATE);
		String userId = sharedpreferences.getString("userid", "");

		switch (item.getItemId()) {
		case R.id.cmd_action:

			if (Integer.parseInt(userId) == clickedComment.getUserid()) {
				deleteComment(clickedComment.getId(), Integer.parseInt(userId));
			} else {
				popup_shadow.setVisibility(View.VISIBLE);
				initiateReportCommentPopupWindow();

			}
			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.comments_menu, menu);
		return true;
	}


	private void deleteComment(int commentId, int userId) {
		RequestParams params = new RequestParams();
		params.put("delete", "1");
		params.put("commentid", String.valueOf(commentId));
		params.put("user", String.valueOf(userId));

		ResharyRestClient.post_comment("comments/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						Toast.makeText(getApplicationContext(),
								getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {
						// getComments(comment_mediaId, clickedPosition);
						adapter.remove(clickedComment);
						adapter.notifyDataSetChanged();
					}

				}, this);
	}

	private void rateCommentUp(int commentId) {

		SharedPreferences sharedpreferences = getSharedPreferences(
				"dk.modified.reshary", Context.MODE_PRIVATE);
		String userId = sharedpreferences.getString("userid", "");

		RequestParams params = new RequestParams();
		params.put("user", String.valueOf(userId));
		params.put("vote", "up_" + String.valueOf(commentId));

		ResharyRestClient.post_comment("comments/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						Toast.makeText(getApplicationContext(),
								getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {
					}

				}, this);
	}

	private void rateCommentDown(int commentId) {

		SharedPreferences sharedpreferences = getSharedPreferences(
				"dk.modified.reshary", Context.MODE_PRIVATE);
		String userId = sharedpreferences.getString("userid", "");

		RequestParams params = new RequestParams();
		params.put("userid", String.valueOf(userId));
		params.put("vote", "down_" + String.valueOf(commentId));

		ResharyRestClient.post_comment("comments/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						Toast.makeText(getApplicationContext(),
								getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {
					}

				}, this);
	}

	private ArrayList<ReportCategories> formatCategories(String report_post) {

		ArrayList<ReportCategories> reportCategories = new ArrayList<ReportCategories>();
		try {
			JSONObject jsonObject = new JSONObject(report_post);

			JSONArray jsonCommentsArray = jsonObject
					.getJSONArray("report_posts");

			for (int i = 0; i < jsonCommentsArray.length(); i++) {
				ReportCategories reportParent = new ReportCategories();
				JSONObject currentParent = jsonCommentsArray.getJSONObject(i);
				reportParent.setId(currentParent.getInt("id"));
				reportParent.setReason(currentParent.getString("reason"));
				reportParent.setParentid(currentParent.getInt("parentid"));

				if (!currentParent.isNull("child")) {

					JSONArray childJson = currentParent.getJSONArray("child");
					ArrayList<ReportCategories> reportChildArr = new ArrayList<ReportCategories>();

					for (int j = 0; j < childJson.length(); j++) {

						ReportCategories reportChild = new ReportCategories();
						JSONObject currentChild = childJson.getJSONObject(j);
						reportChild.setId(currentChild.getInt("id"));
						reportChild.setReason(currentChild.getString("reason"));
						reportChild
								.setParentid(currentChild.getInt("parentid"));

						if (!currentChild.isNull("child")) {

							JSONArray grandChildJson = currentChild
									.getJSONArray("child");
							ArrayList<ReportCategories> reportGrandChildArr = new ArrayList<ReportCategories>();

							for (int k = 0; k < grandChildJson.length(); k++) {
								JSONObject currentGrandChild = grandChildJson
										.getJSONObject(k);
								ReportCategories reportGrandChild = new ReportCategories();
								reportGrandChild.setId(currentGrandChild
										.getInt("id"));
								reportGrandChild.setReason(currentGrandChild
										.getString("reason"));
								reportGrandChild.setParentid(currentGrandChild
										.getInt("parentid"));
								reportGrandChildArr.add(reportGrandChild);
							}

							reportChild.setChild(reportGrandChildArr);
						} else
							reportChild.setChild(null);

						reportChildArr.add(reportChild);

					}
					reportParent.setChild(reportChildArr);
				} else
					reportParent.setChild(null);

				reportCategories.add(reportParent);

			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return reportCategories;
	}

	@SuppressWarnings("deprecation")
	private void initiateReportCommentPopupWindow() {
		try {
			// We need to get the instance of the LayoutInflater
			LayoutInflater inflater = (LayoutInflater) this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View layout = inflater.inflate(R.layout.report_popup,
					(ViewGroup) findViewById(R.id.popup_element));
			reportCommentPopupWindow = new PopupWindow(layout,
					ViewGroup.LayoutParams.WRAP_CONTENT,
					ViewGroup.LayoutParams.WRAP_CONTENT, true);
			reportCommentPopupWindow
					.setBackgroundDrawable(new BitmapDrawable());
			reportCommentPopupWindow.setOutsideTouchable(true);

			reportCommentPopupWindow.showAtLocation(layout, Gravity.CENTER, 0,
					0);

			Button cmd_submit_report = (Button) layout
					.findViewById(R.id.cmd_submit_report);
			final Spinner spinner_1 = (Spinner) layout
					.findViewById(R.id.spinner_1);
			CustomSpinnerAdapter spinner_1_adapter = new CustomSpinnerAdapter(
					this, android.R.layout.simple_spinner_item, arrayList);
			spinner_1.setAdapter(spinner_1_adapter);

			CustomSpinnerAdapter spinner_3_adapter;

			final Spinner spinner_2 = (Spinner) layout
					.findViewById(R.id.spinner_2);
			final Spinner spinner_3 = (Spinner) layout
					.findViewById(R.id.spinner_3);

			reportCommentPopupWindow
					.setOnDismissListener(new PopupWindow.OnDismissListener() {

						@Override
						public void onDismiss() {
							reportCommentPopupWindow.dismiss();
							reportCommentPopupWindow = null;
							popup_shadow.setVisibility(View.GONE);
							// end may TODO anything else
						}
					});

			spinner_1.setOnItemSelectedListener(new OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> parent, View view,
						int position, long id) {

					if (arrayList.get(position).getChild() != null) {
						spinner_2.setVisibility(View.VISIBLE);
						CustomSpinnerAdapter spinner_2_adapter;
						spinner_2_adapter = new CustomSpinnerAdapter(
								getApplicationContext(),
								android.R.layout.simple_spinner_item, arrayList
										.get(position).getChild());
						spinner_2_adapter.notifyDataSetChanged();
						spinner_2.setAdapter(spinner_2_adapter);
					} else {
						spinner_2.setVisibility(View.INVISIBLE);
					}
				}

				@Override
				public void onNothingSelected(AdapterView<?> parent) {
					// TODO Auto-generated method stub

				}
			});

			spinner_2.setOnItemSelectedListener(new OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> parent, View view,
						int position, long id) {

					if (arrayList.get(spinner_1.getSelectedItemPosition())
							.getChild().get(position).getChild() != null) {
						spinner_3.setVisibility(View.VISIBLE);
						CustomSpinnerAdapter spinner_3_adapter;
						spinner_3_adapter = new CustomSpinnerAdapter(
								getApplicationContext(),
								android.R.layout.simple_spinner_item, arrayList
										.get(spinner_1
												.getSelectedItemPosition())
										.getChild().get(position).getChild());
						spinner_3_adapter.notifyDataSetChanged();
						spinner_3.setAdapter(spinner_3_adapter);
					} else {
						spinner_3.setVisibility(View.INVISIBLE);
					}

				}

				@Override
				public void onNothingSelected(AdapterView<?> parent) {
					// TODO Auto-generated method stub

				}
			});

			spinner_3.setOnItemSelectedListener(new OnItemSelectedListener() {

				@Override
				public void onItemSelected(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onNothingSelected(AdapterView<?> parent) {
					// TODO Auto-generated method stub

				}
			});
			cmd_submit_report.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {

					ReportCategories selectedItem = null;

					if (spinner_1.isShown()) {
						selectedItem = (ReportCategories) spinner_1
								.getSelectedItem();
					}

					if (spinner_2.isShown()) {
						selectedItem = (ReportCategories) spinner_2
								.getSelectedItem();
					}

					if (spinner_3.isShown()) {
						selectedItem = (ReportCategories) spinner_3
								.getSelectedItem();
					}

					if (selectedItem.getId() == -1) {
						Toast.makeText(getApplicationContext(),
								getString(R.string.spinner_button_prompts),
								Toast.LENGTH_LONG).show();
					} else {
						submitReport(selectedItem.getId(), clickedComment.getId());
						reportCommentPopupWindow.dismiss();
						reportCommentPopupWindow = null;
					}

				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void submitReport(int reportId, int commentId) {
		RequestParams params = new RequestParams();
		SharedPreferences sharedpreferences = getSharedPreferences(
				"dk.modified.reshary", Context.MODE_PRIVATE);
		String securitytoken = sharedpreferences.getString("securitytoken", "");
		String userId = sharedpreferences.getString("userid", "");
		params.add("securitytoken", securitytoken);
		params.add("userid", userId);
		params.add("comment_reporting_scheme_id", String.valueOf(reportId));
		params.add("commentid", String.valueOf(commentId));

		ResharyRestClient.post("report_comment/", params,
				new AsyncHttpResponseHandler() {

					@Override
					public void onFailure(int arg0, Header[] arg1, byte[] arg2,
							Throwable arg3) {
						Toast.makeText(getApplicationContext(),
								getString(R.string.network_error),
								Toast.LENGTH_LONG).show();
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String content) {
						Toast.makeText(getApplicationContext(),
								getString(R.string.comment_report_success),
								Toast.LENGTH_LONG).show();
					}

				}, this);

	}

}
